package com.springcloud.serviceex;




import com.springcloud.controller.MoveController;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import java.util.Timer;
import java.util.TimerTask;


@Slf4j
@Data
@Component
public class DispatchService implements ServletContextListener {
    private String refX;
    private String refY;
    private String refAngle;
    private String power;
    private Timer timer = new Timer();
    private Timer timer2=new Timer();
    private AutoExecute autoExecute;
    public interface AutoExecute{
        void autoCharging();
    }
    public  void  setAutoExecute(AutoExecute autoExecute){
        this.autoExecute=autoExecute;
    }


    public DispatchService() {
        ForkliftService.getInstance().startPing();
        ForkliftService.getInstance().connect();
        ForkliftService.getInstance().startRead();

    }



    @Override
    public void contextInitialized(ServletContextEvent sce) {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                refX=ForkliftService.getInstance().getActX();
                refY=ForkliftService.getInstance().getActY();
                refAngle=ForkliftService.getInstance().getActAngle();
                power=ForkliftService.getInstance().getPower();

            }
        }, 3000, 1000);
       timer2.schedule(new TimerTask() {
           @Override
           public void run() {

               charging();
           }
       },4000,120000);
    }
    //如果需要改进，通过手自动来区分是否需要发送任务
    private void charging() {
        if(power==null||refX==null||refY==null)return;
        double power=Double.parseDouble(this.power);
        double offsetX=Double.parseDouble(this.refX)-6;
        double offsetY=Double.parseDouble(this.refY)-2.5;
        //处于充电桩位置时不用再发充电任务
        while(!(MoveController.abs(offsetX)<0.05&&MoveController.abs(offsetY)<0.05)){
            //电量低于30时发送充电任务
            if (power>5&&power<30){
                MoveController.move2Pile("0113");
                break;
            }
        }

        while(MoveController.abs(offsetX)<0.05&&MoveController.abs(offsetY)<0.05){
            if(power>95){
                MoveController.move2Pile("01130");
                break;
            }
        }
    }


    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ForkliftService.getInstance().stopRead();
        ForkliftService.getInstance().disconnect();
        ForkliftService.getInstance().stopPing();
        timer.cancel();

    }
}
